﻿if ("undefined" == typeof sx) {
    sx = {};
}
if (window.top === window.self) {
    sx.top = window.self;
} else {
    sx.top = window.top.sx.top;
} 
$.extend(sx, {
    resultCode: { ok: 200, error: 300, timeout: 310 }, 
    // --- 根据layer 扩展弹窗 start --- //
    open: function (opt) {
       return layer.open(opt);
       // return sx.top.layer.open(opt);
    },
    alert: function (content, options, yes) {
        var type = typeof options === 'function';
        if (type) yes = options;

        if ("function" == typeof yes) { 
            var yesOld = yes;
            yes = function (index) { layer.close(index); yesOld(index); };
        }
        return layer.alert(content, options, yes);
    }, 
    success: function (content, options, yes) {
        
        var type = typeof options === 'function';
        if (type) yes = options;
        
        return sx.alert(content, $.extend({ icon: 1 }, type ? {} : options), yes);
    },
    error: function (content,options,end) {
        var type = typeof options === 'function';
        if (type) end = options; 
        return sx.alert(content, $.extend({ icon: 2 }, type ? {} : options), end);
    },
    info: function (content, options, yes) {
        var type = typeof options === 'function';
        if (type) yes = options;
        return sx.alert(content, $.extend({ icon: 0 }, type ? {} : options), yes);
    },
    msg: function (content, options, end) {
        return sx.alert(content, options, end);
    },
    load: function (icon, options) {
        return sx.open($.extend({
            type: 3,
            icon: icon || 0,
            resize: false,
            shade: 0.01
        }, options));
    }, 
    tips: function (content, follow, options) {
        return sx.open($.extend({
            type: 4,
            content: [content, follow],
            closeBtn: false,
            time: 3000,
            shade: false,
            resize: false,
            fixed: false,
            maxWidth: 210
        }, options));
    },
    confirm: function (content, options, yes, cancel) { 
        return layer.confirm(content, options, yes, cancel);
    },
    close: function (index) {
        layer.close(index);
    },
    remove: function (yes) {
        sx.confirm("删除后数据不能恢复！是否确认删除？", { btn: ['确认', '取消'] }, yes, function () { });
    },
    /*Iframe 方式弹窗*/
    win: function (opt, callback) {
        var type = typeof opt === 'function';
        if (type) {
            callback = opt; 
            opt = {};
        } 
        var data = opt.data; 
        if ("undefined" == typeof data) {
            data = {};
        }

        var oldOpt = {
            type: 2, 
            fix: false,//不固定
            shade: 0.6,
            shadeClose: false,
            maxmin: true, //开启最大化最小化按钮
            scrollbar: true,
            area: ['640px', '515px'], 
            success: function (layero, index) {
                var iframeWin = layero.find('iframe')[0].contentWindow;
                iframeWin.InputData = data;
                if ("undefined" == typeof iframeWin.sx) {
                    iframeWin.sx = {};
                }
                iframeWin.sx.winIndex = index;
                iframeWin.sx.winLayer = sx.top.layer;
                iframeWin.sx.winLayer.winCallback = callback;
            }
        };
        return sx.top.layer.open($.extend(oldOpt,opt));
    },
    winCancel: function () { sx.winLayer.close(sx.winIndex); },
    winClose : function(data) {
        if ("undefined" != typeof sx.winIndex && "undefined" != typeof sx.winLayer) {
            sx.winLayer.winCallback(data);
            sx.winLayer.close(sx.winIndex);
        }
    },
    // --- 根据layer 扩展弹窗 end--- //

    changeTheme: function (newTheme) {
        var $admintheme = $("#admintheme");
        if ($admintheme.length == 0) {
            $("head").append('<link _href="/miniui/themes/$theme$/skin.css" _curtheme="default" rel="stylesheet" id="admintheme" />');
            $admintheme = $("#admintheme");
        }
        $("#admintheme").attr("href", $("#admintheme").attr("_href").replace("$theme$", newTheme)); 
        var $iframes = $(document).find("iframe");
        if ($iframes.length >0) {
            for (var i = 0; i < $iframes.length ;i++ ){
                var cw = $iframes[i].contentWindow;
                if (cw.sx && cw.sx.changeTheme) {
                    cw.sx.changeTheme(newTheme);
                }
            }
        }
    }
});


/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


/**
* jquery ajax extend
*/ 
// 重写ajax
(function ($) {
    var _ajax = $.ajax;//首先备份下jquery的ajax方法  
    $.ajax = function (opt) {
        var fn = {
            error: function (xhr, status, errorThrown) { },
            success: function (data, textStatus, jqXHR) { },
            complete: function (jqXHR, textStatus) { }
        };
        if (opt.error) {
            fn.error = opt.error;
        }
        if (opt.success) {
            fn.success = opt.success;
        }
        if (opt.complete) {
            fn.complete = opt.complete;
        }
        var _opt = $.extend(opt, {
            error: function (xhr, status, errorThrown) {
                if (xhr.status === 401) {
                    mini.showMessageBox({ 
                        width: 250,
                        title: "未授权异常", 
                        message: "1、请确保登录或者登录没有过期;<br/>2、确保当前账号有访问该接口权限。",
                        iconCls: "mini-messagebox-error", 
                    });
                } 
                var $errrorhtml = $(xhr.responseText);
                var errorTitle = '';
                var errorComment = '';
                for (var i = 0; i < $errrorhtml.length; i++) {
                    if ($(xhr.responseText)[i].nodeName.toUpperCase() === "TITLE") {
                        errorTitle = $(xhr.responseText)[i].innerText;
                    }
                    if ($(xhr.responseText)[i].nodeName.toUpperCase() === "#COMMENT") {
                        errorComment = $(xhr.responseText)[i].textContent;
                    }
                } 
                fn.error(xhr, status, errorThrown);
            },
            success: function (data, textStatus, jqXHR) { 
                fn.success(data, textStatus, jqXHR);
            },
            complete: function (jqXHR, textStatus) { 
                fn.complete(jqXHR, textStatus);
            }
        });
        return _ajax(_opt);
    }
})(jQuery);

/**
* 导出功能
*/ 
$.extend(sx,
    {
        ExportByGrid: function (where, grid, url, title) { 
            function getColumns(columns) {
                var result = {};
                for (var i = 0; i < columns.length; i++) {
                    var column = columns[i];
                    if (column.field) {
                        result[column.field] = column.header;
                    }
                }
                return result;
            }
            var columns = getColumns(grid.getBottomColumns());
            sx.Export(where, columns, url, title);
        },
        Export: function (data, columns, url, title) {
            var $exportForm = $("#excelForm");
            if ($exportForm.length == 0) {
                $("body").append('<form id="excelForm" action="' + url + '" method="post" target="excelIFrame"></form>');
                $("body").append('<iframe id="excelIFrame" name="excelIFrame" style="display: none;"></iframe>');
                $exportForm = $("#excelForm");
            } else {
                $exportForm.attr("action", url);
            }
            $exportForm.empty();
            var json = mini.encode(columns);
            var $hidColumns = $('<input type="hidden" name="columns"/>');
            $hidColumns.val(json);
            $exportForm.append($hidColumns);
            for (var p in data) {
                if (typeof (data[p]) != "function") {
                    var $hidField = $('<input type="hidden" name="' + p + '"/>');
                    $hidField.val(data[p]);
                    $exportForm.append($hidField);
                }
            }
            $exportForm.append('<input type="hidden" name="title" value="' + title + '"/>');
            $exportForm.submit();
        }
    }
); 
// 关闭miniui的调试模式 
mini_debugger = false;
